using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using Cinemachine;



struct KSSPlayerInput{
    public bool Action0;//抓头 之类的
    public bool Action1;//抠脚 之类的
    public float XVelocity;
    public float YVelocity;
    
}
public class P_KSS : MonoBehaviour
{
    [SerializeField]
    public float speed = 1.25f;
    [SerializeField]
    public Animator anim;

    [SerializeField]
    public Vector2 rightActionPos;
    [SerializeField]
    public Vector2 leftActionPos;
    [SerializeField]
    public float actionDistance = 0.2f;

    private Rigidbody2D rb;
    private BoxCollider2D cc;



    
    private string IDLE = "idle";
    private string RUN = "run";
    private string FALLING = "falling";

    /// 通过玩家输入的速度
    private Vector2 faceDir = Vector2.right;

    private string stateName = "";
    private void Awake() {
        Change2State(IDLE);
    }

    private void Change2State(string stateName) {
        this.stateName = stateName;
        anim.Play(stateName, 0, 0);
        // anim.Play(stateName, 0);
        Debug.Log("当前状态,播放动画"+stateName);
    }

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        cc = GetComponent<BoxCollider2D>();
    }

    public void Reset() {
        transform.position = new Vector3(0f,0f,0f);
        // GetComponent<Collider2D>().isTrigger = ;
        isDead = false;
        Change2State(IDLE);
    }

    KSSPlayerInput playerInput;
    /// <summary>
    /// 收集输入
    /// </summary>
    void GatherInput() {
        playerInput.Action0 = Input.GetButton("Fire1");
        playerInput.Action1 = Input.GetKey(KeyCode.Space);
        playerInput.XVelocity = 0;
        playerInput.YVelocity = 0;
        if (Input.GetKey(KeyCode.A)) {
            playerInput.XVelocity += -speed;
        }
        if (Input.GetKey(KeyCode.D)) {
            playerInput.XVelocity += speed;
        }
        if (Input.GetKey(KeyCode.W)) {
            playerInput.YVelocity += speed;
        }
        if (Input.GetKey(KeyCode.S)) {
            playerInput.YVelocity += -speed;
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (isDead)
            return;
        GatherInput();
        
        if (stateName == IDLE) {
            if (playerInput.XVelocity != 0 || playerInput.YVelocity != 0) {
                Change2State(RUN);
                rb.velocity = new Vector2(playerInput.XVelocity, playerInput.YVelocity);
                SetFaceByXV();
            }

            HandleAction0();
        }

        if (stateName == RUN) {
         
            SetFaceByXV();
            rb.velocity = new Vector2(playerInput.XVelocity, playerInput.YVelocity);

            HandleAction0();
        }



    
    }

    /// <summary>
    /// 处理动作0
    /// </summary>
    void HandleAction0()
    {
        if (playerInput.Action0)
        {
            if (faceDir == Vector2.right)
            {
                var ret = Physics2D.Raycast((Vector2)transform.position + rightActionPos, Vector2.right, actionDistance, 1 << LayerMask.NameToLayer("NPC"));
                if (ret.collider != null)
                {
                    Debug.Log(ret.transform.gameObject.name);
                }
            }
            else
            {
                var ret = Physics2D.Raycast((Vector2)transform.position + leftActionPos, Vector2.left, actionDistance, 1 << LayerMask.NameToLayer("NPC"));
                if (ret.collider != null)
                {
                    Debug.Log(ret.transform.gameObject.name);
                }
            }
        }
    }

    /// <summary>
    /// 物理update主要处理，物理信息变化方面的操作，比如速度变成0，然后受重力下落之类的
    /// </summary>
    private void FixedUpdate() {
        
    }  

    private void SetFace(Vector2 dir)
    {
        if (faceDir != dir) {
            transform.Rotate(0.0f, 180.0f, 0.0f);
            faceDir = dir;
        }
    }
    ///通过X方向速度V来设置face
    private void SetFaceByXV()
    {
        if (playerInput.XVelocity == 0)
            return;
        if (playerInput.XVelocity > 0) {
            SetFace(Vector2.right);
        }
        else {
            SetFace(Vector2.left);
        }
    }


    #region 屏幕抖动处理
    private bool isDead = false;
    private System.Threading.CancellationTokenSource cts;
    public void PlayDie() {
        isDead = true;
        rb.velocity = Vector2.zero;
        // GetComponent<Collider2D>().isTrigger = true;
        StartCoroutine(Shake());
    }
    
    Vector3 originPos;
    private static int SHAKE_TOTAL_TIMES = 30;
    private static int shakeTimes = 0;
    IEnumerator Shake() {
        originPos = transform.position;
        shakeTimes=0;
        while (true) {
            transform.position = new Vector3(originPos.x + UnityEngine.Random.Range(-0.15f, 0.15f), originPos.y + UnityEngine.Random.Range(-0.15f, 0.15f), transform.position.z);
            yield return new WaitForEndOfFrame();
            shakeTimes++;
            if (shakeTimes >= SHAKE_TOTAL_TIMES) {
                transform.position = originPos;
                originPos = transform.position;
                break;
            }
        }
        yield return new WaitForSeconds(0.2f);

        Material material = GetComponent<Renderer>().sharedMaterial;
        DOTween.To(() => material.GetFloat("_Fade"), x => material.SetFloat("_Fade", x), 0, 1.0f);
        yield return new WaitForSeconds(1f);
        
        //GameUI.ComMain.Instance.ComGameOver.visible = true;
    }

    #endregion


    #region Gizmos
    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawLine(rightActionPos, rightActionPos + new Vector2(actionDistance, 0));
        Gizmos.DrawLine(leftActionPos, leftActionPos - new Vector2(actionDistance, 0));
        // Gizmos.DrawWireCube(groundCheck.position, groundCheckVec);
    }

    private void OnDrawGizmosSelected() {
        Gizmos.color = Color.red;
        // Gizmos.DrawWireCube(normalLandHitOffset, normalLandHitSize);
        
        Gizmos.color = Color.yellow;
        // Gizmos.DrawWireCube(normalAirHitOffset, normalAirHitSize);
    }
    #endregion



    #region 帧事件
    private void HitHandle(RaycastHit2D hit) {
    
    }
    #endregion

}
